<template>
    <div class="holding-wrap">
        <el-table
            :data="tableData"
            class="my-table"
            row-class-name="table-row">
            <el-table-column
                label="合约">
                <template slot-scope="scope">
                    <span class="icon empty"
                    :class='{"more": scope.row.long}'>{{scope.row.long ? '多':'空'}}
                    </span> {{getCurPaireObj.label}}  <span class="blue">{{scope.row.leverage}}X</span>
                </template>
            </el-table-column>
            <el-table-column
                prop=""
                label="持仓量">
                <template slot-scope="scope">
                  {{scope.row.size}}&nbsp;{{getCurPaireObj.token}}
                </template>
            </el-table-column>
            <el-table-column
                prop=""
                width="200"
                label="开仓均价">
                <template slot-scope="scope">
                  {{scope.row.openPrice | fck(-8, 2)}}&nbsp;USDT
                </template>
            </el-table-column>
            <el-table-column
                prop=""
                label="当前价格">
                <template slot-scope="scope">
                  {{curPrice}}&nbsp;USDT
                </template>
            </el-table-column>
            <el-table-column
                prop=""
                label="未实现盈亏(回报率)">
                <template slot-scope="scope">
                    <span class="green">{{user.unrealizedPnl | fck(-8, 2)}}&nbsp;USDT</span>
                </template>
            </el-table-column>
            <el-table-column
                prop=""
                label="持仓保证金">
                <template slot-scope="scope">
                    {{user.positionMargin | fck(-8, 2)}}
                </template>
            </el-table-column>
            <el-table-column
                prop=""
                label="保证金率">
                {{marginRatio | fck(0, 2)}}
            </el-table-column>
            <el-table-column
                prop=""
                label="预估强平价">
                <template slot-scope="scope">
                    <span class="red">--（--%）</span>
                </template>
            </el-table-column>
            <el-table-column
                prop=""
                class=""
                label="">
                <template slot="header">
                    <div class="pointer yellow link" @click="closeAll">一键平仓</div>
                </template>
                <template slot-scope="scope">
                    <div class="input">
                        <template v-if="scope.row.long">
                            <input class="borderless" v-model="longSize"></input>
                        </template>
                        <template v-else>
                            <input class="borderless" v-model="shortSize"></input>
                        </template>
                        <button class="btn pc-btn" @click="handleClosePosition(scope.row)">平仓</button>
                    </div>
                </template>
            </el-table-column>
            <el-table-column
                prop=""
                width="120"
                label="设置止盈/止损">
                <template slot-scope="scope">
                    <div class="pointer" @click="editPosition(scope.row)">—/—<i class="icon edit-icon"></i>
                    </div>
                </template>
            </el-table-column>
        </el-table>


        <el-dialog
            title="设置止盈止损"
            :visible.sync="showDialog"
            :lock-scroll="false"
            class="black-dialog medium-dialog settings-dialog"
            width="30%">
            <div class="dialog-form">
                <div class="row">
                    <div class="item">
                        开仓均价
                        <span class="float-right">
                            {{curPosition.openPrice | fck(-8, 2)}}
                            <span class="unit">USDT</span>
                        </span>
                    </div>
                    <div class="item">
                        当前价格
                        <span class="float-right">{{curPrice}}
                            <span class="unit">USDT</span>
                        </span>
                    </div>
                </div>
                <div class="row input-row">
                    <div class="border-box flex-hor-layout">
                        <div class="">止盈</div>
                        <input type="number" class="input borderless"
                            v-model="curPosition.upPrice" placeholder="请输入">
                        <div class="">USDT</div>
                    </div>
                </div>
                <div class="tips" v-show="curPosition.upPrice">
                    当合约价格达到<span class="price">{{curPosition.upPrice}}</span>
                    时，将会触发市价平仓当前仓位。预计盈利为
                    <span class="green">{{upAmount}}&nbsp;USDT</span>
                </div>
                <div class="row input-row">
                    <div class="border-box flex-hor-layout">
                        <div class="">止损</div>
                        <input type="number" class="input borderless"
                            v-model="curPosition.downPrice" placeholder="请输入">
                        <div class="">USDT</div>
                    </div>
                </div>
                <div class="tips" v-show="curPosition.downPrice">
                    当合约价格达到<span class="price">{{curPosition.downPrice}}</span>
                    时，将会触发市价平仓当前仓位。预计亏损为
                    <span class="red">{{downAmount}}&nbsp;USDT</span>
                </div>
                <div class="row btn-row flex-hor-layout">
                    <div class="btn cancel-btn pointer" @click="showDialog = false">取 消</div>
                    <div class="btn ok-btn pointer" @click="handlePosition">确 定</div>
                </div>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import { mapGetters } from 'vuex'
import ToastUtils from '@/utils/toastUtils'
import {transferAttr2Int, fck} from '@/filters'
export default {
    name: 'Home',
    components: {
    },
    data() {
        return {
            curPosition: {

            },
            showDialog: false,
            tableData: [],
            longSize: '',
            shortSize: ''
        }
    },
    computed: {
      ...mapGetters([
        'addr',
        'board',
        'account',
        'curPrice',
        'user'
      ]),
      upAmount(){
        let upPrice = fck(this.curPosition.upPrice, 8, 2)
        let openPrice = parseFloat(this.curPosition.openPrice)
        let size = parseFloat(this.curPosition.size)
        log('holding.vue/upAmount', {upPrice, openPrice, size})
        if(upPrice > openPrice) {
            return fck((upPrice - openPrice) * size, -8, 2)
        }
        return '--'
    },
    downAmount(){
        let downPrice = fck(this.curPosition.downPrice, 8, 2)
        let openPrice = parseFloat(this.curPosition.openPrice)
        let size = parseFloat(this.curPosition.size)
        log('holding.vue/downAmount', {downPrice, openPrice, size})
        if(downPrice < openPrice) {
            return fck((openPrice - downPrice) * size, -8, 2)
        }
        return '--'
    }
    },
    watch: {
      'account': function(newVal) {
        // console.log('holding.vue==>>watch.account, newVal: %o', newVal)
        this.tableData = []
        if(newVal.long && parseFloat(newVal.long.size) > 0){
          const val = Object.assign({},newVal.long)
          val.long = true
          val.upPrice = ''
          val.downPrice = ''
          this.tableData.push(val)
        }
        if(newVal.short && parseFloat(newVal.short.size) > 0){
          const val = Object.assign({},newVal.short)
          val.long = false
          val.upPrice = ''
          val.downPrice = ''
          this.tableData.push(val)
        }
      }
    },
    created() {
    },
    mounted() {

    },
    methods:{
        closeAll(){
            ToastUtils.showMsg('此功能尚未开放')
        },
        handleClosePosition(position){
            console.log('holding/index.vue==>>handleClosePosition, positon: %o', position)
            const {_size} = transferAttr2Int({
                _size: position.long ? this.longSize : this.shortSize
            }, ['_size'], [])
            if(_size <= 0){
                ToastUtils.showMsg('请填写平仓量')
                return
            }
            const _side = position.long ? 0 : 1
            window.closePosition(_side, _size, 0)
                .then(res => {
                    console.log('holding/index.vue==>>handleClosePosition.closePosition, res: %o', res)
                    var id = setInterval(()=>{
                    getInfoByTransaction(res, (err, data) => {
                        console.log('holding/index.vue==>>handleClosePosition.closePosition.getInfoByTransaction err: %o, data: %o', err, data)
                        if(!err){
                            if(data.block) {
                            this.$store.dispatch('user/updateAccount', this.addr)
                            ToastUtils.showMsg('平仓操作成功')
                            clearInterval(id)
                            }
                        }else{
                            ToastUtils.showMsg('平仓操作失败')
                        }
                        })
                    }, 2000)
                })
                .catch(err => {
                    console.log('holding/index.vue==>>handleClosePosition.closePosition, err: %o', err)
                })
        },
        editPosition(position){
            // ToastUtils.showMsg('此功能尚未开放')
            this.showDialog = true
            this.curPosition = position
        },
        handlePosition(){
            const rs = transferAttr2Int(this.curPosition,
                ['size', 'leverage', 'openPrice'], ['upPrice', 'downPrice'])
            const {size, upPrice, downPrice, leverage, openPrice} = rs
            log('holding.vue.handlePosition', {curPosition: this.curPosition, rs})
            let _side = this.curPosition.long ? 0 : 1

            let showMsg = true
            if(upPrice > openPrice) {
                log('holding.vue.handlePosition.upPrice', {upPrice})
                window.closePosition(size, size, upPrice)
                    .then(res=> {
                        log('holding.vue.handlePosition.upPrice', {res})
                    })
                    .catch(err=>{
                        log('holding.vue.handlePosition.upPrice', {err})
                    })
                this.showDialog = false
                showMsg = false
            }
            if(downPrice > 0 && downPrice < openPrice) {
                log('holding.vue.handlePosition.downPrice', {downPrice})
                window.closePosition(size, size, downPrice)
                    .then(res=> {
                        log('holding.vue.handlePosition.downPrice', {res})
                    })
                    .catch(err=>{
                        log('holding.vue.handlePosition.downPrice', {err})
                    })
                this.showDialog = false
                showMsg = false
            }

            if(showMsg) {
                ToastUtils.showMsg('请填写正确的止盈/止损价')
            }
        }
    }
}
</script>
<style lang="scss" scoped>
@import "./index.scss";
</style>
